<template>
  <el-dialog title="分配角色" :visible="showRole" @close="cancel">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="assignRoles">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPeopleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  props: {
    showRole: {
      type: Boolean,
      default: false
    },
    userId: { // 用户的id 用来查询当前用户的角色信息
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [], // 所有角色列表
      roleIds: []// 当前用户角色
    }
  },
  created() {
    this.getPeopleList()
  },
  methods: {
    // 获取所有角色
    async getPeopleList() {
      const { rows } = await getPeopleList({ page: 1, pagesize: 100 })
      this.list = rows
    },
    // 根据id获取角色
    async getUserDetailById(id) {
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds
    },
    // 取消
    cancel() {
      this.roleIds = [] // 清空原来的数组
      this.$emit('update:showRole', false)
    },
    // 给用户分配角色
    async assignRoles() {
      await assignRoles({ id: this.userId, roleIds: this.roleIds })
      this.cancel() // 关闭窗体
      this.$message.success('分配角色成功!')
    }
  }
}
</script>

<style>

</style>
